import React, { useState, useEffect } from 'react';
import { Icon, Button, Table, message, Popconfirm, Input, Menu, Dropdown, Modal } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import { getCustomList, postCustomStatus, deleteCustom, getCustomSum } from '@api/knowledge';
import FingerPrintForm from './form';
import './index.less';

const prefixCls = 'custom-fingerprint';
const Search = Input.Search;
const { confirm } = Modal;

// eslint-disable-next-line react/prop-types
function CustomFingerprint() {
  const [count, setCount] = useState(0);
  const [filter, setFilter] = useState({ page: 1, pageSize: 10 });
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [detail, setDetail] = useState();
  const [maxSum, setMaxSum] = useState(0);
  const [useSum, setUseSum] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [userList, setUserList] = useState([]);

  function getList() {
    setLoading(true);
    getCustomList(filter)
      .then(res => {
        const data = _.get(res, 'data.data.list', []);
        const count = _.get(res, 'data.data.count', 0);
        setUserList(
          _.get(res, 'data.data.userList', []).map(r => {
            return { value: r._id, text: `${r.username}` };
          })
        );
        setDataSource(data);
        setCount(count);
      })
      .catch(() => {
        message.error('获取列表失败！');
      })
      .finally(() => {
        setLoading(false);
      });
    getCustomSum().then(r => {
      setMaxSum(_.get(r, 'data.data.limit', 10));
      setUseSum(_.get(r, 'data.data.used', 0));
    });
  }
  useEffect(() => {
    getList();
  }, [filter]);

  const handleDeleteDict = ids => {
    setLoading(true);
    deleteCustom({ idList: ids.ids })
      .then(() => {
        message.success('删除成功！');
        getList();
        setSelectedRowKeys([]);
      })
      .catch(() => {
        message.error('删除失败');
        setLoading(false);
      });
  };

  const onTableChange = (pagination, filters, sorter) => {
    setSelectedRowKeys([]);
    const { columnKey } = sorter;
    let params = {
      ...filter,
      page: pagination.current,
      pageSize: pagination.pageSize,
      enable: filters.enable || [],
      userIdList: filters.nickname || []
      // createdTimeSort: sorter.order === 'ascend' ? 'ASC' : 'DESC',
      // updateTimeSort: sorter.order === 'ascend' ? 'ASC' : 'DESC'
    };
    columnKey === 'updated'
      ? (params.updateTimeSort = sorter.order === 'ascend' ? 'ASC' : 'DESC')
      : delete params.updateTimeSort;

    columnKey === 'created'
      ? (params.createTimeSort = sorter.order === 'ascend' ? 'ASC' : 'DESC')
      : delete params.createTimeSort;

    setFilter(params);
  };

  const columns = [
    {
      title: '规则名称',
      dataIndex: 'name'
    },
    {
      title: '服务',
      dataIndex: 'service'
    },
    {
      title: '组件',
      dataIndex: 'product'
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      render: created => moment(created).format('YYYY-MM-DD HH:mm:ss'),
      sorter: (a, b) => a.created - b.created
    },
    {
      title: '更新时间',
      dataIndex: 'updated',
      render: updated => moment(updated).format('YYYY-MM-DD HH:mm:ss'),
      sorter: (a, b) => a.updated - b.updated
    },
    {
      title: '创建人',
      dataIndex: 'nickname',
      className: 'vulner-is-build-in',
      render: (username, row) => {
        const name = _.get(row, 'userOid.username');
        const nickname = _.get(row, 'userOid.nickname');
        return name && nickname ? (
          <div>
            {nickname}({name})
          </div>
        ) : (
          '暂无创建人'
        );
      },
      filters: userList,
      // filterMultiple: false,
      filteredValue: filter.userIdList || []
    },
    {
      title: '状态',
      dataIndex: 'enable',
      render: enable => {
        return (
          <>
            <Icon
              style={{ color: enable ? 'green' : 'red', fontSize: 16, marginRight: 5 }}
              type={enable ? 'check-circle' : 'close-circle'}
            />
            {enable ? '已启用' : '已禁用'}
          </>
        );
      },
      filters: [{ text: '已启动', value: true }, { text: '已禁用', value: false }],
      filterMultiple: false,
      filteredValue: filter.enable || []
    },
    {
      title: '操作',
      render: record => (
        <div>
          <Button type="link">
            <a
              onClick={() => {
                setDetail(record);
                setVisible(true);
              }}
            >
              编辑
            </a>
          </Button>
          <Popconfirm
            placement="bottomRight"
            title={'确定删除选择的规则吗？'}
            onConfirm={() => handleDeleteDict({ ids: [record._id] })}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" style={{ color: 'red' }}>
              删除
            </Button>
          </Popconfirm>
        </div>
      )
    }
  ];

  const onMenuClick = ({ key }) => {
    let item = ~~key ? '启用' : '禁用';
    confirm({
      title: `批量${~~key ? '启用' : '禁用'}指纹规则`,
      content: <div style={{ marginLeft: -37 }}>确定{item}所选的指纹规则吗?</div>,
      okText: '确认',
      cancelText: '取消',
      icon: '',
      className: 'custom-modal-confirm',
      onOk() {
        postCustomStatus({ idList: selectedRowKeys, enable: ~~key ? true : false })
          .then(() => {
            message.success('操作成功');
            setSelectedRowKeys([]);
            getList();
          })
          .catch(() => {
            message.error('操作失败');
          });
      }
    });
  };

  const tablTips = () => {
    let tips;
    maxSum < 0
      ? (tips = `当前共有“${useSum}”个指纹规则`)
      : (tips = `当前共有“${useSum}”个指纹规则,还可添加“${
          maxSum - useSum < 0 ? 0 : maxSum - useSum
        }”个指纹规则`);
    return <div className={`${prefixCls}-header-count`}>{tips}</div>;
  };

  const menu = (
    <Menu onClick={onMenuClick}>
      <Menu.Item key={1}>启用</Menu.Item>
      <Menu.Item key={0}>禁用</Menu.Item>
    </Menu>
  );

  const rowSelection = {
    onChange: selectedRowKeys => {
      setSelectedRowKeys(selectedRowKeys);
    },
    getCheckboxProps: record => ({
      disabled: record.isBuiltIn
    })
  };

  return (
    <div className={prefixCls}>
      <div className={`${prefixCls}-page-title`}>自定义指纹</div>
      <div className={`${prefixCls}-operate`}>
        <div>
          <Button
            type="primary"
            disabled={useSum >= maxSum && maxSum >= 0}
            onClick={() => setVisible(true)}
          >
            添加指纹规则
          </Button>
          <Popconfirm
            placement="bottomRight"
            disabled={selectedRowKeys.length === 0}
            title={'确定删除选择的规则吗？'}
            onConfirm={() => handleDeleteDict({ ids: selectedRowKeys })}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="danger"
              className={`${prefixCls}-operate-btn`}
              disabled={selectedRowKeys.length === 0}
              loading={loading}
              style={{ marginRight: 15 }}
            >
              删除
            </Button>
          </Popconfirm>
          <Dropdown overlay={menu} disabled={selectedRowKeys.length === 0}>
            <Button>
              编辑 <Icon type="down" />
            </Button>
          </Dropdown>
        </div>
        <div>
          <Search
            enterButton
            placeholder="请输入规则名称搜索"
            allowClear
            onSearch={value => {
              setFilter({ ...filter, page: 1, searchName: value.trim() });
            }}
          />
        </div>
      </div>
      <div>
        {tablTips()}
        <Table
          rowKey={record => record._id}
          rowSelection={{ ...rowSelection, selectedRowKeys }}
          loading={loading}
          columns={columns}
          pagination={{
            total: count,
            current: filter.page,
            pageSize: filter.pageSize,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showSizeChanger: true,
            showTotal: num => `共 ${num} 条`,
            size: 'small'
          }}
          dataSource={dataSource}
          // getPopupContainer={triggerNode => triggerNode.parentNode}
          onChange={onTableChange}
        />
      </div>
      <FingerPrintForm
        visible={visible}
        setVisible={setVisible}
        getList={getList}
        detail={detail}
        setDetail={setDetail}
      />
    </div>
  );
}

export default CustomFingerprint;
